<?php
/**
 * Akimimi front
 * VoteService
 * by M.Wang
 */
require_once ('../app/core/services/BaseService.php');
require_once '../app/models/CommentDao.php';
require_once '../app/models/ProductDao.php';
require_once '../app/models/ProductItemDao.php';
require_once '../app/models/OrderDao.php';
require_once '../app/models/OrderItemDao.php';

class VoteService extends BaseService{
    /**
     * @var CommentDao
     */
    private $commentDao;
    private $orderDao;
    private $productDao;
    private $productItemDao;
    private $orderItemDao;
    
    public function __construct($components=array()){
        parent::__construct($components);
        $this->commentDao = new CommentDao($this->dbUtil);
        $this->orderDao = new OrderDao($this->dbUtil);
        $this->productDao = new ProductDao($this->dbUtil);
        $this->productItemDao = new ProductItemDao($this->dbUtil);
        $this->orderItemDao = new OrderItemDao($this->dbUtil);
    }

    /**
     * Get StarView instance
     *
     * @return StarView
     */
    protected function getStarViewObject(){
        require_once '../app/views/StarView.php';
        return new StarView();
    }

    /**
     * @param array $arr_param
     * @return string|boolean
     */
    public function saveComments( $arr_param ){
        if( $this->commentDao->insertComment( $arr_param ) ){
            require_once '../app/services/UserPointService.php';
            require_once '../app/constants/UserConstants.php';
            $cid = AAService::getCustomer();
            $userPointService = new UserPointService();
            $userPoints = $userPointService->getUserTodayPoints( $cid, 3 );
            if( $userPoints < 200 && strlen($arr_param["content"]) > 25 ){
//            if( $userPoints < 200 && mb_strlen($arr_param["content"], 'utf-8') > 15 ){
                $userPointService->updatePoint($cid,10,UserConstants::getAddUserPointCause(3));
            }
            $starView = $this->getStarViewObject();
            return $starView->getThanksMessage();
        }
        return false;
    }

    /**
     * @param int $int_productid
     * @return string
     */
    public function getStarPointForm( $int_productid, $currentPage=1 ){
    	$itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $float_avgPoint = $this->commentDao->getProductAvgPoint($int_productid);
        $arr_comments = $this->commentDao->getCommentsByProductId($int_productid, ($currentPage-1)*$itemsPerPage, $itemsPerPage);
        $opinionAllNum = $this->commentDao->getCommentsNumberByProductId($int_productid);
        $starView = $this->getStarViewObject();
        return $starView->getStarBox( $float_avgPoint, $int_productid, $arr_comments ,$opinionAllNum );
    }
    
    /**
     * product页面只显示第一条评价
     * @param int $int_productid
     * @return string
     */
    public function getFirstPointForm( $int_productid, $itemIdStrings ){
    	$userId = AAService::getCustomer();
        $float_avgPoint = $this->commentDao->getProductAvgPoint($int_productid);
        //get the first opinion from comment table
        $arr_comments = $this->commentDao->getTopOneCommentsByProductId($int_productid, 0, 1);
        $orderInfo = $this->orderDao->getOpinionUserInfoFirstByUserIdAndItemIds($userId, $itemIdStrings);
        $opinionAllNum = $this->commentDao->getCommentsNumberByProductId($int_productid);
        $starView = $this->getStarViewObject();
//        return $starView->getStarBox( $float_avgPoint, $int_productid, $arr_comments ,$opinionAllNum );
        return $starView->getFirstStarBox( $float_avgPoint, $int_productid, $arr_comments, $opinionAllNum, $orderInfo );
    }

    public function getCommentsView( $int_productid ){
    	$itemsPerPage = $GLOBALS["config"]['items_per_page'];
        $arr_comments = $this->commentDao->getCommentsByProductId($int_productid, 0, $itemsPerPage);
        $starView = $this->getStarViewObject();
        return $starView->getComments( $arr_comments );
    }

    /**
     * @param int $int_productid products.id
     * @return string
     */
    public function getAvgStarPointView( $int_productid ){
        $float_avg = $this->commentDao->getProductAvgPoint($int_productid);
        $starView = $this->getStarViewObject();
        return $starView->getStatic($float_avg);
    }
    
    public function getCommentsNumberByProductId($int_productid = 0){
        $opinionAllNum = $this->commentDao->getCommentsNumberByProductId($int_productid);
        return $opinionAllNum[0]["opinionNumber"];
    }
	
    /**
     * 求当前产品的评论人数
     */
    public function getCommentsUserNumberByProductId($int_productid = 0){
    	$result = $this->commentDao->getCommentsUserNumberByProductId($int_productid);
        $opinionUserAllNum = count($result);
    	return $opinionUserAllNum;
    }
    
    /**
     * 求所有产品的所有评论信息或指定产品的所有评论信息
     */
    public function getAllCommentsByProductId($int_productid = 0, $int_page=null, $int_limit=null){
        $result = array();
        //得到评论，回复，用户信息等内容
    	$commentInfos = $this->commentDao->getAllCommentsByProductId($int_productid, $int_page, $int_limit);
    	foreach ($commentInfos as $commentInfo) {
    		$itemIds = "";
    		$productId = $commentInfo["product_id"];
    		//根据pid得到所有product表信息
    		$productInfos = $this->productDao->getByProductId($productId);
    		$productTitle = $productInfos[0]["title"];
    		$productUrlTitle = $productInfos[0]["url_title"];
    		//根据pid得到所有itemid
    		$productItemInfos = $this->productItemDao->getByProductId($productId);
    		foreach ($productItemInfos as $productItemInfo) {
    			$itemIds .= $productItemInfo["id"].",";
    		}
    		$itemIds = substr($itemIds, 0, (strlen($itemIds)-1) );
    		//根据所有itemid找到最新的order_id来显示评论中的订单信息
    		$orderInfo = $this->orderItemDao->getLatestOrderInfoByItemIds($itemIds);
    		$latestOrderId = $orderInfo[0]["order_id"];
    		//根据orderid找到订单信息
    		$orderInfos = $this->orderDao->getOrderById($latestOrderId);
    		$shippingKey = $orderInfos[0]["shipping_expect"];
    		$shippingTitle = Order::getShippingMethod($shippingKey);
	        $paymentKey = $orderInfos[0]["payment_method"];
	        $paymentTitle = Order::getPaymentMethod($paymentKey);
    		$userrank = self::getUserRank($commentInfo["userrank"]);
	        $result[] = array("shippingTitle" => $shippingTitle,
	                           "productUrlTitle" => $productUrlTitle,
	                           "productTitle" => $productTitle,
	                           "paymentTitle" => $paymentTitle,
					           "buyTime" => $orderInfos[0]["created"],
					           "username" => $commentInfo["username"],
					           "userrank" => $userrank,
					           "userranknum" => $commentInfo["userrank"],
					           "content" => $commentInfo["content"],
					           "created" => $commentInfo["created"],
					           "reply_content" => $commentInfo["reply_content"],
					           "reply_created" => $commentInfo["reply_created"]
	                   );
    	}
    	return $result;
    }
    
    /**
     * 得到评论总数
     */
    public function getOpinionNumber($int_productid = 0){
    	$commentInfos = $this->commentDao->getAllCommentsNumberByPid($int_productid);
    	return $commentInfos[0]["num"];
    }
    
    
    /**
     * Get user rank
     * 
     * @return string
     */
    private function getUserRank($rank){
        if($rank == 1){
            return CUSTOMERRANK1;
        }elseif($rank == 2){
            return CUSTOMERRANK2;
        }elseif($rank == 3){
            return CUSTOMERRANK3;
        }elseif($rank == 4){
            return CUSTOMERRANK4;
        }elseif($rank == 5){
            return CUSTOMERRANK5;
        }elseif($rank == 6){
            return CUSTOMERRANK6;
        }else{
            return "";
        }
    } 
    
    

    /*
 * Steve
 */
    
/**
     * Get comments by user_id
     *
     * @param int $int_userid
     * @param int $int_page
     * @param int $int_limit
     * @return array
     */
    public function getCommentsByUserId( $int_userid, $int_page, $int_limit ){
    	$arr_comments = $this->commentDao->getCommentInfoByUserId( $int_userid, $int_page, $int_limit );
    	if( $arr_comments ){
    	   $arr_comments['Count'] = $this->dbUtil->getLastFoundRows();
    	   $arr_comments['Count'] = $arr_comments['Count'][0]['ROWS'];
    	}
    	return $arr_comments;
    }

}
?>
